import os
from flask import Flask, Blueprint, render_template, send_from_directory, request
from apps.modules.main.views.article import article_bp
from apps.modules.main.views.page import page_bp
from apps.modules.main.views.category import category_bp
from apps.modules.main.views.tag import tag_bp
from apps.modules.admin.models.cms.cms_post import Post
from apps.extensions import db
from apps.common.utils import get_active_theme_name
from apps.modules.main.views.chat import chat_bp

# 获取当前文件所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))

# 创建main
main_bp = Blueprint('main',
                    __name__,
                    url_prefix='/',
                    template_folder='templates')


def register_main_bps(app: Flask):
    app.register_blueprint(main_bp)
    app.register_blueprint(article_bp)
    app.register_blueprint(page_bp)
    app.register_blueprint(tag_bp)
    app.register_blueprint(category_bp)
    app.register_blueprint(chat_bp)

    # 自定义静态文件路由，避免与 Flask 默认静态文件路由冲突
    @app.route('/main-static/<path:filename>')
    def main_static(filename):
        static_folder = os.path.join(current_dir, 'templates')
        return send_from_directory(static_folder, filename)
    

@main_bp.route('/')
def index():
    """首页"""
    return render_template(get_active_theme_name() + '/index.html')

@main_bp.route('/about')
def about():
    """关于页面"""
    return render_template(get_active_theme_name() + '/about.html')


@main_bp.route('/contact')
def contact():
    """联系页面"""
    return render_template(get_active_theme_name() + '/contact.html')


@main_bp.route('/post/<slug>')
def post_detail(slug):
    """文章详情页面"""
    # 根据slug获取文章
    post = Post.query.filter_by(slug=slug, status='published').first()
    
    if not post:
        return render_template(get_active_theme_name() + '/errors/404.html'), 404
    
    # 增加阅读量
    if not hasattr(post, 'views'):
        post.views = 0
    post.views += 1
    db.session.commit()
    
    # 获取相关文章（同分类的其他文章）
    related_posts = []
    if post.category:
        related_posts = Post.query.filter(
            Post.category_id == post.category_id,
            Post.id != post.id,
            Post.status == 'published'
        ).order_by(Post.created_at.desc()).limit(3).all()
    
    return render_template(get_active_theme_name() + '/post_detail.html',
                         post=post,
                         related_posts=related_posts)
